<template>
	<view class="box-border">
		<view class="u-tag clearfixed">
			<block v-for="(item, index) in selectlist" :key="index">
				<view class="tag-label" @click="del(index)">
					{{ item }}
				</view>
			</block>
		</view>
		<view>
			<input
				ref="inputRef"
				:focus="inputFocus"
				class="input-tag"
				maxlength="50"
				:disabled="disabled"
				v-model="inputzy"
				type="text"
				:placeholder="placeholder"
				@confirm="confirm"
				@blur="blurText"
			/>
		</view>
	</view>
</template>
<script>
export default {
	data() {
		return {
			inputFocus: false,
			inputzy: "",
		}
	},
	props: {
		selectlist: {
			type: Array,
			default: function () {
				return []
			},
		},
		placeholder: {
			type: String,
			default: "",
		},
		disabled: {
			type: Boolean,
			default: false,
		},
	},
	watch: {
		inputzy(news, olds) {
			var key = news.trim()
			var title = key
			if (news[0] == " " || news[0] == "," || news[0] == "，") {
				var title = news.split(news[0])[1]
				this.inputzy = title
				return
			}
			if (
				(news.length != "1" && news[news.length - 1] == " ") ||
				news[news.length - 1] == "," ||
				news[news.length - 1] == "，"
			) {
				title = key.split(news[news.length - 1])[0]
				title = title.trim()
				var obj = this.selectlist.find((item) => item.title == title)
				if (obj) {
					this.inputzy = ""
					return
				}
				this.selectlist.push({
					title,
				})
				this.inputzy = ""
				this.change()
			}
		},
	},
	methods: {
		confirm(e) {
			if (this.selectlist.length >= 10) {
				uni.showToast({
					title: "最多输入10条！",
					icon: "none",
				})
				return false
			}
			this.changeVal(e.detail.value)
		},
		changeVal(news) {
			var key = news.trim()
			if (key == "") {
				this.inputzy = ""
				return
			}
			var title = key
			var obj = this.selectlist.find((item) => item == title)
			if (obj) {
				this.inputzy = ""
				return
			}
			this.selectlist.push(title)
			this.inputzy = ""
			this.change()
			this.inputFocus = false
			setTimeout(() => {
				this.inputFocus = true
			}, 300)
		},
		blurText(e) {
			this.changeVal(e.detail.value)
		},
		del(index) {
			this.selectlist.splice(index, 1)
			this.change()
		},
		change() {
			this.$emit("change", this.selectlist)
		},
	},
}
</script>
<style scoped lang="scss">
.clearfixed::after {
	content: "";
	display: block;
	clear: both;
}

.box-border {
	width: 100%;
	border-radius: 8upx;
	box-sizing: border-box;
	padding: 10rpx 0;
}

/*
	 *  u-tag
	 */
.u-tag {
	.tag-label {
		position: relative;
		float: left;
		padding-right: 50upx;
		height: 50upx;
		line-height: 50upx;
		border-radius: 4upx;
		background: #38bfff;
		color: #fff;
		padding-left: 20upx;
		margin-right: 20upx;
		margin-bottom: 30upx;

		&::after {
			position: absolute;
			content: "×";
			margin-top: -2upx;
			right: 20upx;
		}
	}
}

.input-tag {
	line-height: 50upx;
}
</style>
